#include "Mesh.h"

Mesh::Mesh()
: VBOs(NULL), VBOCount(0),
IBOs(NULL), IBOCount(0)
{
	m_filesPath = NULL;
	m_fileNames = NULL;
	m_fileCount = 0;
}

Mesh::Mesh(FWuint count, char* path, char* name)
: VBOs(NULL), VBOCount(0),
IBOs(NULL), IBOCount(0)
{
	m_filesPath = path;
	m_fileNames = name;
	m_fileCount = count;
}

Mesh::~Mesh()
{
	SAFE_DEL_ARRAY(m_filesPath);
	SAFE_DEL_ARRAY(m_fileNames);
}

FWint Mesh::Init()
{
	if (m_fileCount == 0)
		return -1;

	std::string file = BASE_SRC_PATH + std::string(m_filesPath) + std::string(m_fileNames);

	//Load file data
	FILE *f = fopen(file.c_str(), "rb");
	if (!f)
	{
		LOGE("File %s isn't exists.\n", file);
		return -1;
	}
	Vertex* vertices;
	FWuint vertexCount;
	FWuint* indices;
	FWuint indexCount;
	fscanf(f, NUM_STRING, &vertexCount);
	ModelTextHelper helper = ModelTextHelper();
	vertices = helper.ReadVertices(f, vertexCount);
	fscanf(f, NUM_STRING, &indexCount);
	indices = helper.ReadIndices(f, indexCount);
	fclose(f);

	//Init data
	//Load vertices
	VBOCount = vertexCount;
	VBOs = new FWuint(1);
	glGenBuffers(1, VBOs);
	glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*vertexCount, vertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	//Load indices
	IBOCount = indexCount;
	IBOs = new FWuint(1);
	glGenBuffers(1, IBOs);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBOs[0]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(FWuint)* indexCount, indices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	SAFE_DEL_ARRAY(vertices);
	SAFE_DEL_ARRAY(indices);

	return 0;
}

void Mesh::Destroy()
{
	glDeleteBuffers(1, VBOs);
	SAFE_DEL_ARRAY(VBOs);
	glDeleteBuffers(1, IBOs);
	SAFE_DEL_ARRAY(IBOs);
}